import json
import logging
import requests
from django.conf import settings
from django.utils import timezone
from requests.exceptions import RequestException

logger = logging.getLogger(__name__)


class FeishuService:
    """飞书渠道推送服务类"""
    
    @classmethod
    def send_feishu_message(cls, webhook_url, message_content, title=None):
        """
        向飞书发送消息
        
        参数:
            webhook_url: 飞书机器人的webhook地址
            message_content: 消息内容
            title: 消息标题（可选）
        """
        if not webhook_url:
            logger.warning("飞书webhook地址为空，无法发送消息")
            return False
        
        # 构建飞书消息格式
        payload = {
            "msg_type": "text",
            "content": {
                "text": message_content
            }
        }
        
        # 如果有标题，构建更丰富的消息格式
        if title:
            payload = {
                "msg_type": "post",
                "content": {
                    "post": {
                        "zh_cn": {
                            "title": title,
                            "content": [
                                [
                                    {
                                        "tag": "text",
                                        "text": message_content
                                    }
                                ]
                            ]
                        }
                    }
                }
            }
        
        headers = {
            'Content-Type': 'application/json'
        }
        
        try:
            response = requests.post(
                webhook_url,
                json=payload,
                headers=headers,
                timeout=10
            )
            
            if response.status_code == 200:
                result = response.json()
                if result.get('code') == 0:
                    logger.info(f"飞书消息发送成功，webhook: {webhook_url}")
                    return True
                else:
                    logger.warning(f"飞书消息发送失败，错误码: {result.get('code')}, 消息: {result.get('msg')}")
                    return False
            else:
                logger.error(f"飞书消息发送失败，状态码: {response.status_code}, 响应: {response.text}")
                return False
                
        except RequestException as e:
            logger.error(f"飞书消息发送异常，webhook: {webhook_url}, 错误: {str(e)}")
            return False
    
    @classmethod
    def send_announcement_notification(cls, project, announcement):
        """
        发送公告通知到飞书
        
        参数:
            project: 项目对象
            announcement: 公告对象
        """
        # 获取项目的飞书webhook配置
        feishu_config = cls._get_project_feishu_config(project)
        if not feishu_config:
            return
        
        message_content = f"""📢 新公告通知

项目：{project.name}
公告标题：{announcement.title}
公告内容：{announcement.content}
发布时间：{timezone.now().strftime('%Y-%m-%d %H:%M:%S')}
"""
        
        cls.send_feishu_message(
            feishu_config['webhook_url'],
            message_content,
            title=f"📢 {project.name} - 新公告"
        )
    
    @classmethod
    def send_webhook_message_notification(cls, project, webhook_message):
        """
        发送webhook消息通知到飞书
        
        参数:
            project: 项目对象
            webhook_message: webhook消息对象
        """
        # 获取项目的飞书webhook配置
        feishu_config = cls._get_project_feishu_config(project)
        if not feishu_config:
            return
        
        # 格式化消息内容
        message_content = cls._format_webhook_message(webhook_message)
        
        cls.send_feishu_message(
            feishu_config['webhook_url'],
            message_content,
            title=f"🔗 {project.name} - Webhook消息"
        )
    
    @classmethod
    def _get_project_feishu_config(cls, project):
        """
        获取项目的飞书配置
        
        参数:
            project: 项目对象
            
        返回:
            dict: 飞书配置信息，包含webhook_url等
        """
        # 从项目的元数据或配置中获取飞书webhook地址
        # 这里可以扩展为从项目配置、环境变量或数据库中获取
        
        # 临时实现：从项目的webhook配置中查找飞书类型的webhook
        feishu_webhooks = project.webhooks.filter(
            is_active=True,
            url__contains='open.feishu.cn'
        )
        
        if feishu_webhooks.exists():
            webhook = feishu_webhooks.first()
            return {
                'webhook_url': webhook.url,
                'channel': webhook.channel
            }
        
        # 如果没有找到飞书webhook，检查项目是否有飞书配置
        project_config = getattr(project, 'feishu_config', {})
        if isinstance(project_config, dict) and project_config.get('webhook_url'):
            return project_config
        
        return None
    
    @classmethod
    def _format_webhook_message(cls, webhook_message):
        """
        格式化webhook消息内容
        
        参数:
            webhook_message: webhook消息对象
            
        返回:
            str: 格式化的消息内容
        """
        # 提取消息标题和内容
        title = webhook_message.title if hasattr(webhook_message, 'title') else 'Webhook消息'
        content = webhook_message.content if hasattr(webhook_message, 'content') else str(webhook_message)
        
        # 如果是字典格式，转换为字符串
        if isinstance(content, dict):
            content = json.dumps(content, ensure_ascii=False, indent=2)
        
        return f"""🔗 Webhook消息推送

消息标题：{title}
消息内容：{content}
接收时间：{timezone.now().strftime('%Y-%m-%d %H:%M:%S')}
"""